<audio id="player" controls></audio>

<div class="input-container">
  <input type="text" id="tts-input" placeholder="输入文本..." />
  <button id="tts-submit-button">发送文本</button>
</div>

<script>
  // 发送文本到后端并播放返回的音频
  document
    .getElementById("tts-submit-button")
    .addEventListener("click", async () => {
      const ttsInputValue = document.getElementById("tts-input").value.trim();
      if (!ttsInputValue) return; // 如果输入为空，则不处理

      try {
        const response = await fetch("http://localhost:5000/tts", {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({ text: ttsInputValue }), // 将输入内容作为JSON发送
        });

        if (!response.ok) {
          throw new Error(`请求失败，状态码：${response.status}`);
        }

        // 获取返回的音频文件
        const audioBlob = await response.blob();
        const audioUrl = URL.createObjectURL(audioBlob);

        // 播放音频
        const audioPlayer = document.getElementById("player");
        audioPlayer.src = audioUrl;
        audioPlayer.play();
      } catch (error) {
        console.error("发生错误:", error);
      }
    });
</script>
